package com.fragments;

import java.util.ArrayList;
import java.util.Iterator;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.ListView;
import android.widget.TextView;

import com.Utility.MessageManager;
import com.Utility.Utility;
import com.Utility.WebServiceCommunicator.WebServiceFlag;
import com.activities.AddContactActivity;
import com.activities.ContactAcitivity;
import com.activities.EditContactActivity;
import com.activities.ImportGmailActivity;
import com.activities.group.TabContactGroupActivity;
import com.adapters.ContactsAdapter;
import com.adapters.db.ContactTableAdapter;
import com.adapters.db.ContentProviderDB;
import com.controls.ws.ContactWSControl;
import com.dialogs.DeleteConfirmDialog;
import com.dialogs.LoadingDialog;
import com.events.WebServiceCommunicatorListener;
import com.objects.Contact;
import com.objects.ContactCheck;
import com.senditcertified.mail.R;
import com.views.ACheckBox;
import com.views.ACheckBox.OnCheckListener;

public class MyContactFragment extends BaseFragment implements OnClickListener,
		OnCheckListener, WebServiceCommunicatorListener {
	public static final int SORT_NAME = 0;
	public static final int SORT_EMAIL = 1;
	private ListView mLstContact;
	private TextView mTvNodata;
	private ACheckBox mCbAll;
	private View mVAddContactTop, mVAddContactBottom, mVImportGmailTop,
			mVImportGmailBottom, mVDeleteContactTop, mVDeleteContactBottom,
			mVColContactName, mVColContactEmail;
	private DeleteConfirmDialog mDeleteConfirmDialog;
	private ContactWSControl mWSContact;
	private LoadingDialog mDialog;
	private ContactsAdapter mAdapter;
	private ContactTableAdapter mTAContact;
	private ContactAcitivity mContactActivity;// father Activity

	@Override
	protected int initLayout() {
		return R.layout.fragment_my_contact;
	}

	@Override
	protected void initViews() {
		mCbAll = (ACheckBox) getView().findViewById(R.id.checkbox);
		mTvNodata = (TextView) getView().findViewById(R.id.tv_nodata);
		mLstContact = (ListView) getView().findViewById(R.id.list);
		View groupButtonTop = getView().findViewById(R.id.ln_group_button_top);
		View groupButtonBottom = getView().findViewById(
				R.id.ln_group_button_bottom);

		mVAddContactTop = groupButtonTop.findViewById(R.id.ln_add_contact);
		mVAddContactBottom = groupButtonBottom
				.findViewById(R.id.ln_add_contact);
		mVImportGmailTop = groupButtonTop.findViewById(R.id.ln_import_gmail);
		mVImportGmailBottom = groupButtonBottom
				.findViewById(R.id.ln_import_gmail);
		mVDeleteContactTop = groupButtonTop
				.findViewById(R.id.ln_delete_contact);
		mVDeleteContactBottom = groupButtonBottom
				.findViewById(R.id.ln_delete_contact);
		mVColContactName = getView().findViewById(R.id.tv_col_contact_name);
		mVColContactEmail = getView().findViewById(R.id.tv_col_email);
	}

	private void setAdapter(ArrayList<ContactCheck> lstItem) {
		if (lstItem != null && lstItem.size() > 0) {
			mAdapter = new ContactsAdapter(getActivity(), mCbAll, lstItem) {
				@Override
				public void onViewEdit(int pos) {
					Intent i = new Intent(
							getActivity().getApplicationContext(),
							EditContactActivity.class);
					i.putExtra(EditContactActivity.KEY_CONTACT_ITEM,
							mAdapter.getItem(pos));
					((TabContactGroupActivity) getActivity().getParent())
							.startChildActivity(
									EditContactActivity.class.getSimpleName(),
									i);
				}
			};
			mTvNodata.setVisibility(View.GONE);
			mLstContact.setVisibility(View.VISIBLE);
			mLstContact.setAdapter(mAdapter);
		} else {
			mTvNodata.setVisibility(View.VISIBLE);
			mLstContact.setVisibility(View.GONE);
			mAdapter = null;
		}

	}

	public void getData() {
		ArrayList<ContactCheck> lst = getContactItemsSort();
		if (lst != null && lst.size() > 0) {
			setAdapter(lst);
		}
		mWSContact.getContacts(Utility.getStringPreference(getActivity(),
				Utility.KEY_LOGIN_TOKEN, ""));
	}

	@Override
	protected void initComponents() {
		// TODO Auto-generated method stub]
		mTAContact = new ContactTableAdapter(getActivity());
		mWSContact = new ContactWSControl(getActivity(), this);
		mContactActivity = (ContactAcitivity) getActivity();
		getData();
	}

	public ArrayList<ContactCheck> getContactItemsSort() {
		String sortOrder = null;
		if (mContactActivity.getContactSortType() == SORT_NAME) {
			if (mContactActivity.isContactNameAsc()) {
				sortOrder = ContentProviderDB.COL_TITLE + " ASC";
			} else {
				sortOrder = ContentProviderDB.COL_TITLE + " DESC";
			}
		} else {
			if (mContactActivity.isContactEmailAsc()) {
				sortOrder = ContentProviderDB.COL_EMAIL + " ASC";
			} else {
				sortOrder = ContentProviderDB.COL_EMAIL + " DESC";
			}
		}
		return mTAContact.getItemsCheck(sortOrder);
	}

	@Override
	protected void addListener() {
		mVAddContactTop.setOnClickListener(this);
		mVAddContactBottom.setOnClickListener(this);
		mVImportGmailTop.setOnClickListener(this);
		mVImportGmailBottom.setOnClickListener(this);
		mVDeleteContactTop.setOnClickListener(this);
		mVDeleteContactBottom.setOnClickListener(this);
		mVColContactEmail.setOnClickListener(this);
		mVColContactName.setOnClickListener(this);
		mCbAll.setOnCheckListener(this);
	}

	@Override
	public void onClick(View v) {
		if (v == mVDeleteContactBottom || v == mVDeleteContactTop) {
			if (mAdapter != null && mAdapter.getCount() > 0) {
				final String deleteOr = mAdapter.getContactChoosed();
				if (deleteOr != null && deleteOr.length() > 0) {
					if (mDeleteConfirmDialog != null) {
						mDeleteConfirmDialog.dismiss();
						mDeleteConfirmDialog = null;
					}
					mDeleteConfirmDialog = new DeleteConfirmDialog(
							getActivity().getParent()) {
						@Override
						public void onConfirm() {
							mWSContact.deleteContacts(Utility
									.getStringPreference(getActivity(),
											Utility.KEY_LOGIN_TOKEN, ""),
									deleteOr);
						}
					};
					mDeleteConfirmDialog.setTitle("Delete Selected Contacts");
					mDeleteConfirmDialog
							.setMessage("Are you sure you wish to remove selected contacts from contact list?");
					mDeleteConfirmDialog.show();
				}
			}

		} else if (v == mVImportGmailTop || v == mVImportGmailBottom) {
			((TabContactGroupActivity) getActivity().getParent()).startChildActivity(
					ImportGmailActivity.class.getSimpleName(), new Intent(
							getActivity().getApplicationContext(),
							ImportGmailActivity.class));
		} else if (v == mVAddContactTop || v == mVAddContactBottom) {
			((TabContactGroupActivity) getActivity().getParent()).startChildActivity(
					AddContactActivity.class.getSimpleName(), new Intent(
							getActivity().getApplicationContext(),
							AddContactActivity.class));
		} else if (v == mVColContactEmail) {
			mContactActivity.setContactEmailAsc(!mContactActivity
					.isContactEmailAsc());
			mContactActivity.setContactSortType(SORT_EMAIL);
			setAdapter(getContactItemsSort());
		} else if (v == mVColContactName) {
			mContactActivity.setContactNameAsc(!mContactActivity
					.isContactNameAsc());
			mContactActivity.setContactSortType(SORT_NAME);
			setAdapter(getContactItemsSort());
		}

	}

	@Override
	public void onConnectionOpen(WebServiceFlag flag) {
		if (flag == WebServiceFlag.GET_CONTACT) {
			if (mAdapter != null && mAdapter.getCount() > 0) {
				return;
			}
		}
		if (mDialog != null) {
			mDialog.dismiss();
			mDialog = null;
		}
		mDialog = new LoadingDialog(getActivity().getParent());
		mDialog.setCancelable(false);
		mDialog.show();

	}

	@Override
	public void onConnectionError(WebServiceFlag flag, String error) {
		if (mDialog != null) {
			mDialog.dismiss();
			mDialog = null;
		}
		MessageManager.showToast(getActivity(), error);
	}

	@Override
	public void onConnectionDone(WebServiceFlag flag, String response) {
		if (mDialog != null) {
			mDialog.dismiss();
			mDialog = null;
		}

		if (flag == WebServiceFlag.GET_CONTACT) {
			ArrayList<ContactCheck> lst = mWSContact
					.parseContactCheck(response);
			mTAContact.clear();
			for (int i = 0; i < lst.size(); i++) {
				try {
					mTAContact.add(lst.get(i), i);
				} catch (Exception e) {
				}
			}
			setAdapter(getContactItemsSort());
		} else if (flag == WebServiceFlag.DELETE_CONTACT) {
			String returnValue = mWSContact.parseAction(response,
					"DeleteContactsFromListResult");
			if (returnValue != null && returnValue.length() > 0) {
				MessageManager.showToast(getActivity(), returnValue);
			}
			mWSContact.getContacts(Utility.getStringPreference(getActivity(),
					Utility.KEY_LOGIN_TOKEN, ""));
		}

	}

	@Override
	public void onDestroyView() {
		if (mWSContact != null) {
			mWSContact.cancel();
			mWSContact = null;
		}
		if (mDialog != null) {
			mDialog.dismiss();
			mDialog = null;
		}
		if (mDeleteConfirmDialog != null) {
			mDeleteConfirmDialog.dismiss();
			mDeleteConfirmDialog = null;
		}
		super.onDestroyView();
	}

	@Override
	public void onCheck(View v, boolean check) {
		if (check) {
			mAdapter.setCheckMode(ContactsAdapter.MODE_CHECK_ALL);
			mAdapter.notifyDataSetChanged();
		} else {
			mAdapter.setCheckMode(ContactsAdapter.MODE_UNCHECK_ALL);
			mAdapter.notifyDataSetChanged();
		}

	}

}
